package com.wise.wing.activity.login;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.bm.corelibs.logic.BaseLogic.NListener;
import com.bm.corelibs.utils.ToastMgr;
import com.wise.wing.R;
import com.wise.wing.activity.logic.LoginManager;
import com.wise.wing.activity.logic.SettingManager;
import com.wise.wing.activity.main.BaseActivity;
import com.wise.wing.activity.main.WebActivity;
import com.wise.wing.activity.tools.SMSBroadcastReceiver;
import com.wise.wing.activity.tools.SMSBroadcastReceiver.MessageListener;
import com.wise.wing.activity.tools.Tools;
import com.wise.wing.bean.BaseData;
import com.wise.wing.constant.Constant;
import com.wise.wing.views.CommonNavigationBar;


public class RegisterActivity extends BaseActivity implements OnClickListener {

	private CommonNavigationBar bar;
	private EditText register_tel;
	private EditText register_psw;
	private Button get_vcode;
	private ImageButton register_agree;
	private TextView register_protocol;
	private Button register_next;
	private Button register_singlelogin;
	private Boolean isCheck = true;
	private LoginManager manager = new LoginManager();
	
	private SettingManager settingManager;

	/**
	 * 倒计时
	 */
	private DownTimer timer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		bar = (CommonNavigationBar) findViewById(R.id.navi);
		bar.setTitle("站点注册");
		bar.setListener(null);
		register_tel = (EditText) findViewById(R.id.register_call);
		register_psw = (EditText) findViewById(R.id.register_psw);
		get_vcode = (Button) findViewById(R.id.register_get_vcode);
		register_agree = (ImageButton) findViewById(R.id.register_agree);
		register_protocol = (TextView) findViewById(R.id.register_protocol);
		register_next = (Button) findViewById(R.id.register_next);
		register_singlelogin = (Button) findViewById(R.id.register_singlelogin);

	}

	@Override
	public void init() {
		timer = new DownTimer(60 * 1000, 1000);
		settingManager=new SettingManager();
	}

	@Override
	public void addListeners() {
		get_vcode.setOnClickListener(this);
		register_agree.setOnClickListener(this);
		register_protocol.setOnClickListener(this);
		register_next.setOnClickListener(this);
		register_singlelogin.setOnClickListener(this);
	}

	/**
	 * 开启定时任务(主要是获取电话验证码)
	 */
	private final class DownTimer extends CountDownTimer {

		public DownTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			// 倒计时开始
			long m = millisUntilFinished / 1000;
			String ss = String.valueOf(m % 3600 % 60);
			ss = twoLength(ss);
			get_vcode.setText(ss + " 秒");
		}

		/**
		 * 如果小于位，加0
		 * 
		 * @param str
		 * @return
		 */
		private String twoLength(String str) {
			if (str.length() == 1) {
				return str = "0" + str;
			}
			return str;
		}

		@Override
		public void onFinish() {
			get_vcode.setClickable(true);
			get_vcode.setText("重发");
		}
	}

	private NListener<BaseData> getVCodeListener() {
		return new NListener<BaseData>() {
			@Override public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
				//	ToastMgr.show("验证码: " + data.data.vCode);
					showToast("验证码已下发,请注意查收");
					get_vcode.setText("59" + " 秒");
					get_vcode.setClickable(false);
					register(data.data.vCode);
					timer.start();
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}
			@Override public void onAllPageLoaded(int nowPage, int totalPage) {}
		};
	}
	
	private NListener<BaseData> checkVCodeListener() {
		return new NListener<BaseData>() {
			@Override public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					Intent intent = new Intent(RegisterActivity.this, SetPasswordActivity.class);
					intent.putExtra("mobile", register_tel.getText().toString());
					startActivity(intent);
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}
			@Override public void onAllPageLoaded(int nowPage, int totalPage) {}
		};
	}

	@Override
	public void onClick(View v) {
	
		switch (v.getId()) {
		case R.id.register_get_vcode:
			if (register_tel.getText().toString().length() == 11 && Tools.validatePhone(register_tel.getText().toString().trim())) {
				loadingDialog.show();
				manager.getVCode(register_tel.getText().toString(), getVCodeListener());
			} else {
				showToast("请输入正确的手机号");
			}
			break;
		case R.id.register_agree:
			if (isCheck) {
				isCheck = false;
			} else {
				isCheck = true;
			}
			setImage(isCheck);
			break;
		case R.id.register_protocol:
			settingManager.getSinglePage("站点端注册协议", new NListener<BaseData>() {

				@Override
				public void onResponse(BaseData data) {
					if (data.status==Constant.STATUS_OK) {
						Intent intent;
						intent = new Intent(RegisterActivity.this, WebActivity.class);
						intent.putExtra("title", "注册协议");
						intent.putExtra("html",data.data.singlePage.content);
						startActivity(intent);
					}
				}

				@Override
				public void onErrResponse(VolleyError error) {
					
				}

				@Override
				public void onAllPageLoaded(int nowPage, int totalPage) {
					
				}
			});
			break;
		case R.id.register_next:
			if (register_tel.getText().toString().length() == 11) {

				if (register_psw.getText().toString().length() >= 6) {

					if (isCheck == true) {
						loadingDialog.show();
						manager.checkVCode(register_tel.getText().toString(), register_psw.getText().toString(), checkVCodeListener());
					} else {
						showToast("需同意注册协议");
					}
				} else {
					showToast("请输入6位验证码");
				}

			} else {
				showToast("请输入11位手机号");
			}

			break;
		case R.id.register_singlelogin:
			startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
			break;
		default:
			break;
		}
	}

	public void setImage(Boolean bl) {
		if (bl) {
			register_agree.setBackgroundResource(R.drawable.register_agree);
		} else {
			register_agree.setBackgroundResource(R.drawable.register_disagree);
		}
	}
	
	private SMSBroadcastReceiver receiver;

	private void register(String code) {
		receiver = new SMSBroadcastReceiver(code, new MessageListener() {
			@Override
			public void onReceived(String message) {
				register_psw.setText(message);
				unRegister();
			}
		});
		IntentFilter intentFilter = new IntentFilter(SMSBroadcastReceiver.SMS_RECEIVED_ACTION);
		intentFilter.setPriority(Integer.MAX_VALUE);
		// 注册广播
		this.registerReceiver(receiver, intentFilter);
	}
	
	private void unRegister() {
		if(receiver != null)
			this.unregisterReceiver(receiver);
		receiver = null;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unRegister();
	}

}
